import {
  useCallback,
  useMemo,
  useState,
  useEffect,
} from 'react'
import { useRequest } from 'ahooks'
import {
  Table,
  Image,
  Tag,
  Button,
  Switch,
} from 'antd'
import { getProjectListApi, postChangeFlagApi } from '@/api/pro'
import { useDetailDrawer } from '@/utils/hooks'

const AppProjectList = () => {
  // 每次刷新都会默认执行一次 ,否则影响数据 , 所以要禁止默认执行
  const { data, loading, run: reGetList } = useRequest(getProjectListApi, { manual: true })

  const [pageInfo, setPageInfo] = useState({ page: '1', pageSize: '10' })
  // 控制页码切换
  const handlePagesize = useCallback((page, pageSize) => {
    setPageInfo({ page, pageSize })
  }, [pageInfo])
  // 控制是否推荐
  const handleFlagChange = useCallback(async ({ proid, isrecommend }) => {
    try {
      await postChangeFlagApi({ type: 'isrecommend', proid, flag: !isrecommend })
      const { page, pageSize } = pageInfo
      reGetList(page, pageSize)
    } catch (error) {
      console.log(error)
    }
  }, [pageInfo])
  // 详情页
  const { drawer, handleDetailOpen } = useDetailDrawer()

  // 重新获取数据
  useEffect(() => {
    const { page, pageSize } = pageInfo
    reGetList(page, pageSize)
  }, [pageInfo])

  const columns = useMemo(() => (
    [
      {
        title: '序号',
        render: (_, record, index) => (pageInfo.page - 1) * (pageInfo.pageSize) + index + 1,
      },
      {
        title: '名称',
        dataIndex: 'proname',
        ellipsis: true,
      },
      {
        title: '图片',
        dataIndex: 'img1',
        render: (_, record, index) => <Image src={_} style={{ width: 100, height: 100 }} />,
      },
      {
        title: '描述',
        dataIndex: 'desc',
        ellipsis: true,
      },
      {
        title: '分类',
        dataIndex: 'category',
        render: (_) => <Tag color={'orange'}>{_}</Tag>,
      },
      {
        title: '品牌',
        dataIndex: 'brand',
        render: (_) => <Tag color={'green'}>{_}</Tag>,
      },
      {
        title: '原价/折扣',
        render: (_) => `${_.originprice}/${_.discount}折`,
      },
      {
        title: '售价',
        render: (_) => _.originprice * _.discount / 10,
      },
      {
        title: '推荐',
        dataIndex: 'isrecommend',
        render: (_, record, index) => <Switch checked={!!_} onChange={() => handleFlagChange(record)} />,
      },
      {
        title: '操作',
        render: (_, record, index) => <Button type="link" onClick={() => handleDetailOpen(record)}>查看</Button>,
      },
    ]
  ), [pageInfo])
  return (
    <>
      <Table rowKey="proid" columns={columns} dataSource={data?.data} loading={loading} pagination={{ total: data?.total, pageSize: '10', onChange: handlePagesize }} />
      { drawer }
    </>
  )
}
export default AppProjectList
